package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    /**
     * 设置Cookie并响应到浏览器
     * @param token
     * @param response
     */
    public static void setToken (String token, HttpServletResponse response){
        //创建出一个Cookie对象,将token存储其中
        Cookie cookie = new Cookie("token",token);

        //设置Cookie的存活时间
        cookie.setMaxAge(RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());

        //设置Cookie的存放路径
        cookie.setPath("/");

        //通过response响应到浏览器
        response.addCookie(cookie);
    }

    /**
     * 获取Cookie
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request){
        String token = null;
        //获取所有的Cookie
        Cookie[] cookies = request.getCookies();
        //判断cookie是否为空
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    token = cookie.getValue();
                    cookie.setPath("/");
                    //延时cookie的存活时间
                    cookie.setMaxAge(RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
                    break;
                }
            }
        }
        return token;
    }

}
